import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { UserItem } from '#/api/system/user';
import { formatDateTime } from '@vben/utils';
import { getRoleSelectList } from '#/api/system/role';
import type { RoleApi } from '#/api/system/role';

import { $t } from '#/locales';

/**
 * 用户基础表单配置（不含密码字段）
 * 用于编辑用户和创建用户的共用部分
 */
export function useBaseUserFormSchema(): VbenFormSchema[] {
  return [
    // 用户基本信息（按重要程度排序）
    {
      component: 'Input',
      fieldName: 'userName',
      label: $t('system.user.userName'),
      rules: 'required',
      componentProps: {
        class: 'col-span-2',
      },
    },
    {
      component: 'Input',
      fieldName: 'realName',
      label: $t('system.user.realName'),
      componentProps: {
        class: 'col-span-2',
      },
    },
    {
      component: 'Input',
      fieldName: 'email',
      label: $t('system.user.email'),
      rules: 'required',
      componentProps: {
        type: 'email',
        class: 'col-span-2',
      },
    },
    {
      component: 'Input',
      fieldName: 'phoneNumber',
      label: $t('system.user.phoneNumber'),
      componentProps: {
        class: 'col-span-3',
      },
    },
    // 用户状态和类型
    {
      component: 'Select',
      componentProps: {
        options: [
          { label: $t('system.user.status_type.normal'), value: 0 },
          { label: $t('system.user.status_type.disabled'), value: 1 },
          { label: $t('system.user.status_type.locked'), value: 2 },
          { label: $t('system.user.status_type.inactive'), value: 3 },
        ],
        class: 'col-span-3',
      },
      defaultValue: 0,
      fieldName: 'status',
      label: $t('system.user.status'),
    },
    {
      component: 'Select',
      componentProps: {
        options: [
          { label: $t('system.user.userType_type.normal'), value: 0 },
          { label: $t('system.user.userType_type.admin'), value: 1 },
          { label: $t('system.user.userType_type.system'), value: 2 },
        ],
        class: 'col-span-12',
      },
      defaultValue: 0,
      fieldName: 'userType',
      label: $t('system.user.userType'),
    },
    // 角色选择
    {
      component: 'ApiSelect',
      fieldName: 'roleIds',
      label: $t('system.user.roles'),
      componentProps: {
        api: getRoleSelectList,
        afterFetch: (roles: RoleApi.RoleSelect[]) => {
          return roles.map(role => ({
            label: role.name,
            value: role.id
          }));
        },
        class: 'col-span-24',
        multiple: true,
        filterable: true,
        placeholder: $t('system.user.selectRoles'),
      }
    },
    // 其他信息
    {
      component: 'Input',
      fieldName: 'nickName',
      label: $t('system.user.nickName'),
      componentProps: {
        class: 'col-span-12',
      },
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: $t('system.user.gender_type.unknown'), value: 0 },
          { label: $t('system.user.gender_type.male'), value: 1 },
          { label: $t('system.user.gender_type.female'), value: 2 },
        ],
        class: 'col-span-12',
      },
      defaultValue: 0,
      fieldName: 'gender',
      label: $t('system.user.gender'),
    },
    {
      component: 'DatePicker',
      fieldName: 'birthDate',
      label: $t('system.user.birthDate'),
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        class: 'col-span-12',
      },
    },
    // 占一整行的个人简介
    {
      component: 'Input',
      fieldName: 'biography',
      label: $t('system.user.biography'),
      componentProps: {
        type: 'textarea',
        class: 'col-span-24',
        rows: 4,
        autosize: { minRows: 4, maxRows: 6 }
      },
    },
  ];
}

/**
 * 编辑用户表单配置
 * 用户名禁用，不含密码字段
 */
export function useFormSchema(): VbenFormSchema[] {
  const baseSchema = useBaseUserFormSchema();

  // 编辑模式下禁用用户名
  return baseSchema.map(item => {
    if (item.fieldName === 'userName') {
      return {
        ...item,
        componentProps: {
          ...item.componentProps,
          disabled: true,
        },
      };
    }
    return item;
  });
}

/**
 * 创建用户表单配置
 * 用户名可编辑，包含密码字段
 */
export function useCreateFormSchema(): VbenFormSchema[] {
  const baseSchema = useBaseUserFormSchema();

  // 添加密码字段（放在用户名之后）
  const userNameIndex = baseSchema.findIndex(item => item.fieldName === 'userName');
  const newSchema = [...baseSchema];

  // 只有在创建用户时才添加密码字段
  newSchema.splice(userNameIndex + 1, 0, {
    component: 'Input',
    fieldName: 'password',
    label: $t('system.user.password'),
    // rules: 'required',
    dependencies: {
      show: (values) => !values.id,
      triggerFields: ['id'],
    },
    componentProps: {
      type: 'password',
      placeholder: $t('system.user.passwordHint'),
      class: 'col-span-24',
    },
  });

  return newSchema;
}

/**
 * 重置密码表单模式
 */
export function useResetPasswordFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'newPassword',
      label: $t('system.user.newPassword'),
      rules: 'required',
      componentProps: {
        type: 'password',
        placeholder: $t('system.user.passwordHint'),
      },
    },
    {
      component: 'Input',
      fieldName: 'confirmPassword',
      label: $t('system.user.confirmPassword'),
      rules: 'required',
      componentProps: {
        type: 'password',
      },
    },
  ];
}

/**
 * 修改密码表单模式
 */
export function useChangePasswordFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'currentPassword',
      label: $t('system.user.currentPassword'),
      rules: 'required',
      componentProps: {
        type: 'password',
      },
    },
    ...useResetPasswordFormSchema(),
  ];
}

/**
 * 查询表单模式
 */
export function useGridFormSchema(): VbenFormSchema[] {
  const commonStyle = {
    width: '100%'
  };

  const commonProps = {
    labelWidth: '70px',
    labelPosition: 'left' as const,
    style: {
      marginBottom: '0'
    }
  };

  return [
    {
      component: 'Input',
      fieldName: 'userName',
      label: $t('system.user.userName'),
      componentProps: {
        ...commonProps,
        style: commonStyle,
        placeholder: $t('system.user.userName'),
        clearable: true
      }
    },
    {
      component: 'Input',
      fieldName: 'email',
      label: $t('system.user.email'),
      componentProps: {
        ...commonProps,
        style: commonStyle,
        placeholder: $t('system.user.email'),
        clearable: true
      }
    },
    {
      component: 'Input',
      fieldName: 'phoneNumber',
      label: $t('system.user.phoneNumber'),
      componentProps: {
        ...commonProps,
        style: commonStyle,
        placeholder: $t('system.user.phoneNumber'),
        clearable: true
      }
    },
    {
      component: 'Select',
      componentProps: {
        ...commonProps,
        allowClear: true,
        options: [
          { color:'primary', label: $t('system.user.status_type.normal'), value: 0 },
          { color:'primary', label: $t('system.user.status_type.disabled'), value: 1 },
          { color:'primary', label: $t('system.user.status_type.locked'), value: 2 },
          { color:'primary', label: $t('system.user.status_type.inactive'), value: 3 },
        ],
        style: commonStyle,
        placeholder: $t('system.user.status'),
        clearable: true
      },
      fieldName: 'status',
      label: $t('system.user.status'),
    },
    {
      component: 'Select',
      componentProps: {
        ...commonProps,
        allowClear: true,
        options: [
          { label: $t('system.user.userType_type.normal'), value: 0 },
          { label: $t('system.user.userType_type.admin'), value: 1 },
          { label: $t('system.user.userType_type.system'), value: 2 },
        ],
        style: commonStyle,
        placeholder: $t('system.user.userType'),
        clearable: true
      },
      fieldName: 'userType',
      label: $t('system.user.userType'),
    },
    {
      component: 'DatePicker',
      fieldName: 'createdTime',
      label: $t('system.user.createdTime'),
      componentProps: {
        ...commonProps,
        style: commonStyle,
        type: 'daterange',
        startPlaceholder: $t('common.startTime'),
        endPlaceholder: $t('common.endTime'),
        valueFormat: 'YYYY-MM-DD',
        unlinkPanels: true,
        defaultTime: [
          new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 2, 1, 23, 59, 59)
        ],
        shortcuts: [
          {
            text: '最近一周',
            value: () => {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              return [start, end];
            }
          },
          {
            text: '最近一个月',
            value: () => {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              return [start, end];
            }
          }
        ]
      }
    },
    {
      component: 'Input',
      fieldName: 'keyword',
      label: $t('common.keyword'),
      componentProps: {
        ...commonProps,
        style: commonStyle,
        placeholder: $t('common.keyword')
      }
    }
  ];
}

/**
 * 表格列配置
 */
export function useColumns<T = UserItem>(
  onActionClick: (params: { code: string; row: T }) => void,
  onStatusChange?: (newStatus: any, row: T) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
  return [
    { align: 'left', title: '', type: 'checkbox', width: 40 },
    { title: '序号', type: 'seq', width: 50 },
    {
      field: 'userName',
      title: $t('system.user.userName'),
      width: 160,
    },
    {
      field: 'realName',
      title: $t('system.user.realName'),
      width: 120,
    },
    {
      field: 'email',
      title: $t('system.user.email'),
      width: 160,
    },
    {
      field: 'phoneNumber',
      title: $t('system.user.phoneNumber'),
      width: 140,
    },
    {
      cellRender: {
        name: 'CellTag',
        options: [
          { value: 0, label: $t('system.user.status_type.normal'), color: 'success' },
          { value: 1, label: $t('system.user.status_type.disabled'), color: 'danger' },
          { value: 2, label: $t('system.user.status_type.locked'), color: 'warning' },
          { value: 3, label: $t('system.user.status_type.inactive'), color: 'info' },
        ]
      },
      field: 'status',
      title: $t('system.user.status'),
      width: 120,
    },
    {
      field: 'userType',
      title: $t('system.user.userType'),
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          { value: 0, label: $t('system.user.userType_type.normal'), color: 'info' },
          { value: 1, label: $t('system.user.userType_type.system'), color: 'info' },
          { value: 2, label: $t('system.user.userType_type.admin'), color: 'info' },
        ]
      },

    },
    {
      field: 'lastLoginTime',
      title: $t('system.user.lastLoginTime'),
      width: 180,
      formatter: ({ cellValue }: { cellValue: string | null | undefined }) => {
        return cellValue ? formatDateTime(cellValue) : '-';
      }
    },
    {
      field: 'lastLoginIp',
      title: $t('system.user.lastLoginIp'),
      width: 120,
    },
    {
      field: 'createdTime',
      title: $t('system.user.createdTime'),
      width: 180,
      formatter: ({ cellValue }: { cellValue: string | null | undefined }) => {
        return cellValue ? formatDateTime(cellValue) : '-';
      }
    },
    {
      field: 'roles',
      title: $t('system.user.roles'),
      width: 100,
      formatter: ({ cellValue }) => {
        if (Array.isArray(cellValue)) {
          return cellValue.join(', ');
        }
        return cellValue;
      },
    },
    {
      align: 'center',
      cellRender: {
        name: 'CellOperation',
        attrs: {
          nameField: 'userName',
          nameTitle: $t('system.user.userName'),
          onClick: onActionClick,
          // 设置主操作按钮，只显示编辑和删除
          mainButtons: ['edit', 'delete'],
          buttons: [
            { code: 'edit', text: $t('common.edit'), type: 'primary' },
            { code: 'delete', text: $t('common.delete'), type: 'danger' },
            { code: 'detail', text: $t('system.user.detail'), type: 'info' },
            { code: 'assignRoles', text: $t('system.user.assignRoles'), type: 'info' },
            { code: 'resetPassword', text: $t('system.user.resetPassword'), type: 'warning' },
            { code: 'changeStatus', text: $t('system.user.changeStatus'), type: 'info' },
          ],
        },
      },
      field: 'operation',
      fixed: 'right',
      title: $t('system.user.operation'),
      width: 200,
    },
  ];
}
